import { createRouter, createWebHistory } from 'vue-router';
import board from '../views/board.vue';
import home from '../views/home.vue';
import login from '../views/login.vue';
import Reg from '../components/reg.vue';
import Login from '../components/Login.vue';
import index from '../views/index.vue';
import lobby from '../views/lobby.vue';
import lobby2 from '../views/lobby2.vue';
import admin from '../views/bms/index.vue';
import UserId from '../components/userId.vue';
import {useUserStore} from "../stores/user";
import useGamestatus from "../stores/game";



const routes = [
{
    path: '/',
    name: 'index',
    component: index,
    beforeEnter: (to, from, next) => {
        let userStore = useUserStore();
        if (userStore.user.username) {
            next();
        } else {
            next('/login');
        }
    }
},
{
    path: '/home',
    name: 'home',
    component: home
},
{
    path: '/board',
    name: 'board',
    component: board,
    beforeEnter: (to, from, next) => {
        let userStore = useUserStore();
        const gamestatus = useGamestatus();

        if (userStore.user.username) {
            if (!gamestatus.myRoomId) {
            console.log("没有加入房间");
            next('/lobby');
        }
            next();
        } else {
            next('/login');
        }
        
    }
},
{
    path: '/lobby',
    name: 'lobby',
    component: lobby,
    beforeEnter: (to, from, next) => {
        let userStore = useUserStore();
        if (userStore.user.username) {
            next();
        } else {
            next('/login');
        }
    }
},
{
    path: '/lobby2',
    name: 'lobby2',
    component: lobby2
},
{
        path: '/login',
        name: 'login',
        component: login,
        children: [
            {
                path: '',
                name: 'login2',
                redirect: { name: 'login1' } // 默认重定向到login1
            },
            {
                path: 'Login',
                name: 'login1',
                component: Login
            },
            {
                path: 'reg',
                name: 'reg',
                component: Reg
            }
        ]

    },
    {
        path: '/admin',
        name: 'admin',
        component: admin,
        beforeEnter: (to, from, next) => {
        let userStore = useUserStore();
        if (userStore.user.username) {
            next();
        } else {
            next('/login');
        }
    }       
    },
    {
        path: '/userId',
        name: 'userId',
        component: UserId        
    }

];


const router = createRouter({
    history: createWebHistory(),
    routes
});

export default router;
